# -* - coding: UTF-8 -* -
#import sys
#reload(sys)
#sys.setdefaultencoding('utf8')

import threading,string
from time import sleep
from task import *
from base_thread import *
import pika
import logging

#从外部队列读取消息放入内部对列
class ManageThread(Thread):  
	def __init__(self,server,commander,service_center):  
		Thread.__init__(self) 
		self.manage_server = server
		self.commander=commander
		self.service_center = service_center
	def on_run(self):
		logging.info("ManageThread Begin")
		try:
			self.manage_server.listen(self.request)
		except Exception as e:
			logging.error('on_run')
			logging.exception(e)
			time.sleep(0.1)
		logging.info("ManageThread End")				
		
	def on_stop(self):
		logging.info('manage_server stop')
		self.manage_server.stop()
		
	def request(self, ch, method, props, body):  #回调
		#,body.decode()
		if body:
			req_str=body.decode()
			logging.info("收到管理消息")#+req_str)
			if req_str.startswith("{") and req_str.endswith("}"):
				self.process_manage(req_str,ch,props)
				
	def process_manage(self,body,ch,props):
		response=''
		task = Task.createFromJson(body)
		if task.checkSign() and task.checkTimes():
			if self.service_center.check(task):
				response = self.service_center.execute(task)
			else:
				#通过FastCGI协议发送给php-fpm执行
				f='command_'+task.command
				if not hasattr(self.commander, f):
					f='command_'+task.plan
				if hasattr(self.commander, f):
					func = getattr(self.commander, f)		#根据函数名获得函数
					if func:
						try:
							response=func(task.data)
						except Exception as e:
							logging.error('process_manage')
							logging.exception(e)
							time.sleep(0.1)					
						
				#sleep(10)
					if ch:
						ch.basic_publish(exchange='',
							 routing_key=props.reply_to,  # props.reply_to从客户端取出双方约定好存放返回结果的queue
							 properties=pika.BasicProperties(correlation_id=props.correlation_id),  # props.correlation_id 从客户端取出当前请求的ID返回给客户端做验证
							 body=str(response))
			
			#循环任务，再次进入队列
			if task.times > 0:
				args={
					'delivery_mode' : 2,
					'headers':{'x-delay':(task.next_time - int(time.time())) * 1000}
				}
				self.manage_server.send(task.toJson(),args)
		return response		

	